<template>
  <div>
    <el-tree :data="Meuns" :props="defaultProps" show-checkbox
    node-key="id" default-expand-all :default-checked-keys="SelectedNodes" ref="tree"></el-tree>
    <el-button @click="onSave">保存</el-button>
  </div>
</template>
<script>
// eslint-disable-next-line
import { GetMenuNodes,getRoleMenus } from '@/services/menu';
// eslint-disable-next-line
import { UpdateRoleMenus} from '@/services/role';

export default {
  name: 'AllocMenu',
  props: {
    id: {
      type: [String, Number],
    },
  },
  created() {
    this.loadMenu();
  },
  data() {
    return {
      Meuns: [],
      UserRoles: [],
      SelectedNodes: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name',
      },
    };
  },
  methods: {
    async loadMenu() {
      const promise1 = getRoleMenus(this.id).then((results) => {
        const { data } = results;
        if (data.code === '000000') {
          this.UserRoles = data.data;
        } else {
          throw new Error('用户菜单列表加载失败');
        }
      });

      const promise2 = GetMenuNodes().then((results) => {
        const { data } = results;
        if (data.code === '000000') {
          this.Meuns = data.data;
        } else {
          throw new Error('菜单列表加载失败');
        }
      });

      Promise.all([promise1, promise2]).then(() => {
        const nodes = [];
        this.UserRoles.forEach((node) => {
          if (!node.selected) {
            return;
          }
          if (node.subMenuList) {
            node.subMenuList.forEach((subnode) => {
              if (subnode.selected) nodes.push(subnode.id);
            });
          }
        });
        this.SelectedNodes = nodes;
      }).catch((error) => {
        console.log(error);
      });

      //
      // const { data } = await GetMenuNodes();
      // if (data.code === '000000') {
      //   this.Meuns = data.data;
      // } else {
      //   this.$message.error('菜单加载失败');
      // }
    },
    async onSave() {
      const subkeys = this.$refs.tree.getCheckedKeys();
      const rootkeys = this.$refs.tree.getHalfCheckedKeys();
      const keys = [...rootkeys, ...subkeys];
      const { data } = await UpdateRoleMenus({ roleId: this.id, menuIdList: keys });
      if (data.code === '000000') {
        this.$message.success('菜单分配成功');
        this.$router.push({ name: 'role' });
      }
    },
  },

};
</script>
